﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using StoragePeriod.Data;
using StoragePeriod.Common;
using StoragePeriod.Web.Common;

namespace StoragePeriod.Web
{
    public partial class Login : SecurityPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string temuname = UtilityUI.GetCookie("SPZCFX_UName");
                string temppass = UtilityUI.GetCookie("SPZCFX_UPass");
                if (!string.IsNullOrEmpty(temppass) && !string.IsNullOrEmpty(temuname))
                {
                    temppass = UtilityUI.Decode(temppass);
                    this.txt_username.Text = temuname;
                    this.txt_password.Attributes["value"] = temppass;
                    this.CK_SavePass.Checked = true;
                }
            }
        }

        public override string PrivCode()
        {
            return "Default";
        }
        protected void btn_submint_Click(object sender, EventArgs e)
        {
            string userName = txt_username.Text.Trim();
            string passWord = txt_password.Text.Trim();
            
            using (CMSCateringDataContext dataContext=new CMSCateringDataContext())
            {
                //bool isPassed = dataContext.user.FirstOrDefault(p => p.UName == userName && p.UPWD == Utility.GetMD5PassWord(passWord,string.Empty)) != null;
                bool isPassed = SYS_Users.Where("UserCode=@0 and UserPWD=@1", userName, Utility.GetMD5PassWord(passWord, "")).FirstOrDefault() != null;
                if (isPassed)
                {
                    FormsAuthentication.SetAuthCookie(userName, false /* createPersistentCookie */);
                    if (this.CK_SavePass.Checked)
                    {
                        UtilityUI.WriteCookie("SPZCFX_UName", userName, 24 * 60);
                        UtilityUI.WriteCookie("SPZCFX_UPass", UtilityUI.Encode(passWord), 24 * 60);
                    }
                    else
                    {
                        UtilityUI.WriteCookie("SPZCFX_UName", userName, -1);
                        UtilityUI.WriteCookie("SPZCFX_UPass", UtilityUI.Encode(passWord), -1);
                    }

                    string RedirectUrl = FormsAuthentication.GetRedirectUrl(userName, false);
                    Response.Redirect(RedirectUrl);
                }
                else
                    Page.Alert("用户名或密码错误");
            }

        }
    }
}